package org.jeecg.basic.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.basic.entity.MesTestunitdetailCfg;
import org.jeecg.basic.entity.MesTestunitheadCfg;
import org.jeecg.basic.vo.MesTestunitheadCfgPage;
import org.jeecg.common.api.CommonAPI;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import com.baomidou.dynamic.datasource.annotation.DS;
import org.jeecg.basic.entity.MesPartDataCfg;
import org.jeecg.basic.service.IMesPartDataCfgService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.qis.entity.MesProcDataCfg;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 换型参数下发
 * @Author: LiCY
 * @Date:   2024-05-17
 * @Version: V1.0
 */
@Api(tags="换型参数下发")
@RestController
@RequestMapping("/basic/mesPartDataCfg")
@Slf4j
public class MesPartDataCfgController extends JeecgController<MesPartDataCfg, IMesPartDataCfgService> {
	@Autowired
	private IMesPartDataCfgService mesPartDataCfgService;

	 @Resource
	 private CommonAPI sysBaseApiImpl;
	
	/**
	 * 分页列表查询666
	 *
	 * @param mesPartDataCfg
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "换型参数下发-分页列表查询")
	@ApiOperation(value="换型参数下发-分页列表查询", notes="换型参数下发-分页列表查询")
	@GetMapping(value = "/list")
	@DS("#header.his")
	public Result<IPage<MesPartDataCfg>> queryPageList(MesPartDataCfg mesPartDataCfg,
													   String partNo,
													   String pnGroup,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<MesPartDataCfg> queryWrapper = QueryGenerator.initQueryWrapper(mesPartDataCfg, req.getParameterMap());
		queryWrapper.in("PARTNO",partNo,pnGroup);
		Page<MesPartDataCfg> page = new Page<MesPartDataCfg>(pageNo, pageSize);
		IPage<MesPartDataCfg> pageList = mesPartDataCfgService.page(page, queryWrapper);
		return Result.OK(pageList);
	}
	
	/**
	 *   添加
	 *
	 * @param mesPartDataCfg
	 * @return
	 */
	@AutoLog(value = "换型参数下发-添加")
	@ApiOperation(value="换型参数下发-添加", notes="换型参数下发-添加")
	//@RequiresPermissions("org.jeecg.modules.demo:mes_part_data_cfg:add")
	@PostMapping(value = "/add")
	@DS("#header.line")
	public Result<String> add(@RequestBody MesPartDataCfg mesPartDataCfg) {
		mesPartDataCfgService.save(mesPartDataCfg);
		return Result.OK("添加成功！");
	}
	
	/**
	 *  编辑
	 *
	 * @param mesPartDataCfg
	 * @return
	 */
	@AutoLog(value = "换型参数下发-编辑")
	@ApiOperation(value="换型参数下发-编辑", notes="换型参数下发-编辑")
	//@RequiresPermissions("org.jeecg.modules.demo:mes_part_data_cfg:edit")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	@DS("#header.line")
	public Result<String> edit(@RequestBody MesPartDataCfg mesPartDataCfg) {
		mesPartDataCfgService.updateById(mesPartDataCfg);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过选中对象删除
	 *
	 * @param mesPartDataCfg
	 * @return
	 */
	@AutoLog(value = "换型参数下发-通过id删除")
	@ApiOperation(value="换型参数下发-通过id删除", notes="换型参数下发-通过id删除")
	//@RequiresPermissions("org.jeecg.modules.demo:mes_part_data_cfg:delete")
	@RequestMapping(value = "/delete")
	@DS("#header.line")
	public Result<String> delete(@RequestBody MesPartDataCfg mesPartDataCfg) {
		mesPartDataCfgService.removeById(mesPartDataCfg);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param list
	 * @return
	 */
	@AutoLog(value = "换型参数下发-批量删除")
	@ApiOperation(value="换型参数下发-批量删除", notes="换型参数下发-批量删除")
	//@RequiresPermissions("org.jeecg.modules.demo:mes_part_data_cfg:deleteBatch")
	@RequestMapping(value = "/deleteBatch")
	@DS("#header.line")
	public Result<String> deleteBatch(@RequestBody List<MesPartDataCfg> list) {
	    list.forEach(item->{
    			mesPartDataCfgService.removeById(item);
    		});
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "换型参数下发-通过id查询")
	@ApiOperation(value="换型参数下发-通过id查询", notes="换型参数下发-通过id查询")
	@GetMapping(value = "/queryById")
	@DS("#header.his")
	public Result<MesPartDataCfg> queryById(@RequestParam(name="id",required=true) String id) {
		MesPartDataCfg mesPartDataCfg = mesPartDataCfgService.getById(id);
		if(mesPartDataCfg==null) {
			return Result.error("未找到对应数据");
		}
		return Result.OK(mesPartDataCfg);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param mesPartDataCfg
    */
    //@RequiresPermissions("org.jeecg.modules.demo:mes_part_data_cfg:exportXls")
    @RequestMapping(value = "/exportXls")
    @DS("#header.his")
    public ModelAndView exportXls(HttpServletRequest request, MesPartDataCfg mesPartDataCfg,String partNo,String pnGroup) {
//		partNo = request.getParameter("partNo");
//		if (StringUtils.isNotBlank(partNo)) {
//			mesPartDataCfg.setPartno(partNo);
//		}
//        return super.exportXls(request, mesPartDataCfg, MesPartDataCfg.class, "换型参数下发");

		// Step.1 组装查询条件查询数据
		//QueryWrapper<MesPartDataCfg> queryWrapper = QueryGenerator.initQueryWrapper(mesPartDataCfg, request.getParameterMap());
		QueryWrapper<MesPartDataCfg> queryWrapper = new QueryWrapper<>();
		queryWrapper.in("PARTNO",partNo,pnGroup);
		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		//配置选中数据查询条件
		String selections = request.getParameter("selections");
		if(oConvertUtils.isNotEmpty(selections)) {
			List<String> selectionList = Arrays.asList(selections.split(","));
			queryWrapper.in("id",selectionList);
		}
		//Step.2 获取导出数据
		List<MesPartDataCfg> mesTestunitheadCfgList = mesPartDataCfgService.list(queryWrapper);

		// Step.4 AutoPoi 导出Excel
		ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
		mv.addObject(NormalExcelConstants.FILE_NAME, "产品下发配置列表");
		mv.addObject(NormalExcelConstants.CLASS, MesPartDataCfg.class);
		mv.addObject(NormalExcelConstants.PARAMS, new ExportParams("产品下发配置数据", "导出人:"+sysUser.getRealname(), "产品样件配置"));
		mv.addObject(NormalExcelConstants.DATA_LIST, mesTestunitheadCfgList);
		return mv;
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    //@RequiresPermissions("mes_part_data_cfg:importExcel")
    @DS("#header.line")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
//        return mesPartDataCfgService.importExcel(request, response, MesPartDataCfg.class);
		MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
		Map<String, MultipartFile> fileMap = multipartRequest.getFileMap();
		for (Map.Entry<String, MultipartFile> entity : fileMap.entrySet()) {
			// 获取上传文件对象
			MultipartFile file = entity.getValue();
			ImportParams params = new ImportParams();
			params.setTitleRows(2);
			params.setHeadRows(1);
			params.setNeedSave(true);
			try {
				List<MesPartDataCfg> list = ExcelImportUtil.importExcel(file.getInputStream(), MesPartDataCfg.class, params);
				//update-begin-author:taoyan date:20190528 for:批量插入数据
				long start = System.currentTimeMillis();
				list.forEach(item -> {
//					item.setRecId()
					String line = item.getLine();
					String op = item.getOp();
					String stn = item.getStn();
					String partNo = item.getPartno();
					String addr = item.getPlcName();
					String name = item.getName();
					String formattedNumber = "";
					formattedNumber = sysBaseApiImpl.getProcSerialNumber(addr);
					Map<String, Object> colMap = new HashMap<>();
					colMap.put("line",line);
					colMap.put("op",op);
					colMap.put("stn",stn);
					colMap.put("partno",partNo);
					colMap.put("name",name);
					List<MesPartDataCfg> dataList = mesPartDataCfgService.listByMap(colMap);
					if (null != dataList && !dataList.isEmpty()) {
						throw new IllegalArgumentException("下发参数重复：" + line+"-"+op+"-"+stn+"-"+partNo+"-"+name + ",已存在！");
					}

					int plcTagAddr = Integer.parseInt(item.getPlcTagAddr());
					String format = String.format("%03d", plcTagAddr);
					String recId = sysBaseApiImpl.getPrefix(line,op,partNo) + format;
					item.setPtdataid(Long.valueOf(recId));
					item.setCtime(new Date());
					mesPartDataCfgService.save(item);
				});
//				mesPartDataCfgService.saveBatch(list);
				//service.saveBatch(list);
				//400条 saveBatch消耗时间1592毫秒  循环插入消耗时间1947毫秒
				//1200条  saveBatch消耗时间3687毫秒 循环插入消耗时间5212毫秒
				log.info("消耗时间" + (System.currentTimeMillis() - start) + "毫秒");
				//update-end-author:taoyan date:20190528 for:批量插入数据
				return Result.ok("文件导入成功！数据行数：" + list.size());
			} catch (Exception e) {
				//update-begin-author:taoyan date:20211124 for: 导入数据重复增加提示
				String msg = e.getMessage();
				log.error(msg, e);
				if (msg != null && msg.indexOf("Duplicate entry") >= 0) {
					return Result.error("文件导入失败:有重复数据！");
				} else {
					return Result.error("文件导入失败:" + e.getMessage());
				}
				//update-end-author:taoyan date:20211124 for: 导入数据重复增加提示
			} finally {
				try {
					file.getInputStream().close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return Result.error("文件导入失败！");
    }

}
